package com.itheima.controller;

import com.itheima.entity.Emp;
import com.itheima.entity.Result;
import com.itheima.service.LonginService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LonginController {
    @Autowired
    private LonginService longinService;
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("用户名：{}，密码：{}", emp.getUsername(), emp.getPassword());
        Emp login = longinService.login(emp);
        if ( login != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", login.getId());
            claims.put("username", login.getUsername());

            String jwt = JwtUtils.generateJwt(claims);
            login.setToken(jwt);
            log.info("令牌:{}", jwt);
            return Result.success(login);
        }
        return Result.error("登录失败,用户名或密码错误！");
    }
}
